<?php

class importPicsTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
    ));

    $this->namespace        = '';
    $this->name             = 'importPics';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [importPics|INFO] task does things.
Call it with:

  [php symfony importPics|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    if ($handle = opendir(sfConfig::get('sf_upload_dir').'/files/')) {
      while (false !== ($file = readdir($handle))) {
          $code = strstr($file, ' ', true);
          if ($code != '') {
            $prod = Doctrine::getTable('Product')->findBy('code', $code);
            if(!$id = $prod[0]['id']) {
              continue;
            }
            $oldName = $file;
            $newName = sha1($file).'.jpg';
            copy(sfConfig::get('sf_upload_dir').'/files/'.$file, sfConfig::get('sf_upload_dir').'/product/'.$newName);
            $pic = new ProductPictures();
            $pic->setParameter('default');
            $pic->setPri(0);
            $pic->setOriginalFilename($oldName);
            $pic->setFile('/product/'.$newName);
            $pic->setProduct($prod[0]);
            $pic->save();
          }
      }
    }
    closedir($handle);exit;
  }
}
